package com.example.chandao.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MybatisPlus 自动填充处理
 */
@Slf4j
@Component
public class MybatisPlusAutoConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = null;
        try {
            userId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            log.info("【MybatisPlus自动插入】未获取到用户ID");
        }
        String finalUserId = userId;
        this.strictInsertFill(metaObject, "createBy", () -> finalUserId, String.class);
        this.strictUpdateFill(metaObject, "updateBy", () -> finalUserId, String.class);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = null;
        try {
            userId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            log.info("【MybatisPlus自动插入】未获取到用户ID");
        }
        String finalUserId = userId;
        this.strictUpdateFill(metaObject, "updateBy", () -> finalUserId, String.class);
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    }

}
